<template>
  <div class="content">
    <el-card class="card-box">
      <div class="card-box--headerwrap">
        <el-page-header content="详情页面" @back="goback"></el-page-header>
        <div class="card-box--setbtn" v-if="isEdit">
          <el-button @click="goback">取消</el-button>
          <el-button type="primary" @click="handleSubmit">保存</el-button>
        </div>
      </div>
    </el-card>
    <el-card class="card-box form-box">
      <div>
        <el-row class="form-info" v-if="route.query.mode !== 'add'">
          <el-col :span="7" :offset="1"
            >创建人: {{ infoState.createUserName }}</el-col
          >
          <el-col :span="7">创建时间: {{ infoState.createTime }}</el-col>
          <el-col :span="8">文档编号: {{ infoState.billNum }}</el-col>
        </el-row>
        <el-form
          ref="formRef"
          :model="formState"
          :rules="Rules"
          label-width="120px"
        >
          <el-form-item
            label="文档名称"
            placeholder="请输入文档名称"
            prop="documentName"
          >
            <el-input
              v-model="formState.documentName"
              :style="{ width: '420px' }"
              :disabled="!isEdit"
            />
          </el-form-item>
          <el-form-item
            label="所属项目"
            placeholder="请选择所属项目"
            prop="projectName"
          >
            <el-select
              :style="{ width: '420px' }"
              v-model="formState.projectName"
              clearable
              placeholder="请选择"
              ref="projectRef"
              :disabled="!isEdit"
            >
              <el-option :value="projectList">
                <el-tree
                  class="tree-option"
                  :data="projectList"
                  accordion
                  node-key="id"
                  ref="projectTreeRef"
                  highlight-current
                  :props="defaultProps"
                  @check-change="handleCheckChange"
                  check-on-click-node
                  :expand-on-click-node="false"
                >
                </el-tree>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="文档类型"
            placeholder="请选择文档类型"
            prop="documentTypeCode"
          >
            <el-cascader
              :style="{ width: '420px' }"
              :disabled="!isEdit"
              v-model="formState.documentTypeCode"
              clearable
              filterable
              :options="documentTypeList"
              :props="documentProp"
              @change="changeType"
              placeholder="输入名称搜索"
            />
          </el-form-item>
          <el-form-item
            label="项目阶段"
            placeholder="请选择项目阶段"
            prop="projectPhaseName"
          >
            <el-select
              :style="{ width: '420px' }"
              v-model="formState.projectPhaseName"
              value-key="dicCode"
              :disabled="!isEdit"
            >
              <el-option
                class="default-option"
                v-for="item in projectPhaseList"
                :label="item.dicValue"
                :key="item.dicCode"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="描述">
            <el-input
              v-model="formState.remarks"
              type="textarea"
              :disabled="!isEdit"
            ></el-input>
          </el-form-item>
          <el-row>
            <el-col :span="12">
              <el-form-item label="上传文档" prop="documentAttachmentArr">
                <el-upload
                  v-if="isEdit"
                  name="uploadFile"
                  multiple
                  :accept="acceptTypes"
                  :action="uploadUrl"
                  :headers="uploadHeaders"
                  :on-change="handleChange"
                  :on-remove="handleRemove"
                  :on-error="handleError"
                  :on-preview="handlePreview"
                  :file-list="defaultFileList"
                  :before-upload="beforeAvatarUpload"
                >
                  <el-button size="small" type="primary">点击上传</el-button>
                  <template #tip>
                    <div class="el-upload__tip">
                      支持上传doc、docx、xls、xlsx、pdf、png、jpg、jpeg等格式文件,文件大小不得大于20M。
                    </div>
                  </template>
                </el-upload>
                <template v-else>
                  <el-link
                    v-for="item in formState.documentAttachmentArr"
                    :key="item?.uuidFile"
                    icon="el-icon-folder"
                    @click.prevent="handleDownload(item)"
                  >
                    {{ item.fileName }}&emsp;
                  </el-link>
                </template>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, computed } from "vue";
import { useRouter, useRoute } from "vue-router";
// import { ElMessage } from "element-plus";
import { storageLocal } from "/@/utils/storage";
import NotifMessage from "/@/utils/message/notification";
import { download } from "/@/utils/download";
import * as api from "/@/api/document";
import { postProjectTree } from "/@/api/acceptance";

import {
  FileTypes
  // ProjectPhaseOptions,
  // DocTypeOptions
} from "../types";
const projectRef = ref<HTMLElement | null>(null) as any;
const projectTreeRef = ref<HTMLElement | null>(null) as any;
const formRef = ref<HTMLFormElement | null>(null) as any;

const router = useRouter();
const route = useRoute();

let projectList = ref([]);
let documentTypeList = ref([]);
let projectPhaseList = ref([]);
const formState = reactive({
  documentName: "",
  projectName: "",
  projectManageId: "",
  documentTypeName: null,
  documentTypeCode: "",
  projectPhaseName: null,
  projectPhaseCode: "",
  remarks: "",
  documentAttachmentArr: []
});

const Rules = {
  documentName: [
    { required: true, message: "请输入文档名称", trigger: "blur" }
  ],
  projectName: [
    { required: true, message: "请选择所属项目", trigger: "change" }
  ],
  documentTypeCode: [
    { required: true, message: "请选择文档类型", trigger: "change" }
  ],
  projectPhaseName: [
    { required: true, message: "请选择项目阶段", trigger: "change" }
  ],
  documentAttachmentArr: [
    { required: true, message: "请上传文档", trigger: "change" }
  ]
};

const defaultProps = {
  children: "children",
  label: "projectName",
  id: "id"
};

let infoState = reactive({
  createTime: "",
  createUserName: "",
  billNum: ""
});

const documentProp = ref({
  label: "documentTypeName",
  children: "children",
  value: "documentTypeCode",
  emitPath: false
});

let isEdit = computed(() => {
  // @ts-ignore
  if (["add", "edit"].includes(route.query.mode)) {
    return true;
  } else {
    return false;
  }
});

const changeType = data => {
  formState.documentTypeCode = data;
  const docObj = getDocTypeAuth(documentTypeList.value, data);
  formState.documentTypeName = docObj.documentTypeName;
  // debugger;
};

const getDocTypeAuth = (nodes, searchKey) => {
  for (let _i = 0; _i < nodes.length; _i++) {
    if (nodes[_i].documentTypeCode === searchKey) {
      return nodes[_i];
    } else {
      if (nodes[_i].children && nodes[_i].children.length > 0) {
        const res = getDocTypeAuth(nodes[_i].children, searchKey);
        if (res) {
          return res;
        }
      }
    }
  }
  return null;
};

/* 上传 -- start */
const acceptTypes = Object.values(FileTypes).join(",");
const uploadUrl =
  import.meta.env.VITE_BASE_URL + "/snow-admin/common/file/upload";
const uploadHeaders = {
  Authorization: storageLocal.getItem("info")?.accessToken
};

let defaultFileList = ref([]);

const handleRemove = (file, fileList) => {
  defaultFileList.value = fileList;
};

const handleChange = (file, fileList) => {
  defaultFileList.value = fileList;
  formRef.value.clearValidate();
};

const handlePreview = file => {
  console.log(file, "file");
  if (file?.response?.code !== 200 || !file?.response?.data) return;
  download(file?.response?.data);
};

const handleError = err => {
  let myError = err.toString(); //转字符串
  myError = myError.replace("Error: ", ""); // 去掉前面的" Error: "
  myError = JSON.parse(myError); //转对象
  myError?.message && NotifMessage.error(myError?.message);

  if (myError?.body?.code && [401, 403].includes(myError?.body?.code)) {
    myError?.body?.message && NotifMessage.error(myError?.body?.message);
    router.push("/login");
    storageLocal.removeItem("info");
  }
};

const handleDownload = item => {
  if (!item) return;
  download(item);
};

const onFilterFileData = (list: any[]) => {
  if (!list || !list.length) return;
  const newFileData = list.map(item => {
    // if (item.status === "success") {
    return item.response.data;
    // }
  });
  return newFileData;
};

const onInitFileList = (list: any[]) => {
  if (!list || !list.length || !list[0]?.fileName) return;
  const newFileList = list.map(item => {
    return {
      name: item?.fileName,
      response: {
        data: item,
        code: 200
      }
    };
  });
  return newFileList;
};

const beforeAvatarUpload = file => {
  // console.log(file);
  const type = file.name.substring(file.name.lastIndexOf(".") + 1);
  if (!Object.keys(FileTypes).includes(type)) {
    NotifMessage.warning(`请上传${Object.keys(FileTypes).join("、")}等格式!`);
    return false;
  }

  const isLt2M = file.size / 1024 / 1024 < 20;

  if (!isLt2M) {
    NotifMessage.warning(`文件大小不能超过20M!`);
    return false;
  }
};
/* 上传 -- end */

const goback = () => {
  router.push("/projectsA/document/manage");
};

const getDetail = async () => {
  const params = {
    id: route.query.id
  };
  const { code, data } = await api.getDocumentInfo(params);
  console.log(code, data, "edit");
  if (code === 200) {
    const {
      createTime,
      createUserName,
      billNum,
      documentName,
      projectName,
      projectManageId,
      documentTypeName,
      documentTypeCode,
      projectPhaseName,
      projectPhaseCode,
      remarks,
      documentAttachmentArr
    } = data;

    infoState.createTime = createTime;
    infoState.createUserName = createUserName;
    infoState.billNum = billNum;

    formState.documentName = documentName;
    formState.projectName = projectName;
    formState.projectManageId = projectManageId;
    formState.documentTypeName = documentTypeName;

    formState.documentTypeCode = documentTypeCode;
    formState.projectPhaseName = {
      dicValue: projectPhaseName,
      dicCode: projectPhaseCode
    };
    formState.projectPhaseCode = projectPhaseCode;
    formState.remarks = remarks;
    formState.documentAttachmentArr = documentAttachmentArr;
    defaultFileList.value = onInitFileList(documentAttachmentArr);
  }
};

const handleSubmit = () => {
  formState.documentAttachmentArr = onFilterFileData(defaultFileList.value);
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      const copyFormData = JSON.parse(JSON.stringify(formState));

      copyFormData.projectPhaseName = formState.projectPhaseName.dicValue;
      copyFormData.projectPhaseCode = formState.projectPhaseName.dicCode;

      console.log("onSave: ", copyFormData);
      if (route.query.mode === "add") {
        const { code, message } = await api.onAdd(copyFormData);
        console.log(code, message);
        if (code === 200) {
          NotifMessage.success("保存成功");
          goback();
        } else {
          NotifMessage.error(message);
        }
      } else {
        const { code, message } = await api.onSave(
          Object.assign(copyFormData, { id: route.query.id })
        );
        console.log(code, message);
        if (code === 200) {
          NotifMessage.success("修改成功");
          goback();
        } else {
          NotifMessage.error(message);
        }
      }
    } else {
      return false;
    }
  });
};

const handleCheckChange = () => {
  const res = projectTreeRef.value.getCurrentNode();
  formState.projectName = [res][0].projectName;
  formState.projectManageId = [res][0].id;
  projectRef.value.blur();
};

// 获取项目信息
const getProjectList = async () => {
  try {
    const { code, data } = await postProjectTree({});
    if (code === 200) {
      projectList.value = data;
    }
  } catch (err) {
    console.log(err);
  }
};

// 文档类型
const initDoucumentTypeList = async () => {
  // try {
  //   const params = {
  //     dicType: "sys_document_type"
  //   };
  const { data } = await api.getTreeDocumentType();
  documentTypeList.value = data;
  //   documentTypeList.value = data;
  //   console.log(code, data);
  // } catch (err) {
  //   console.log(err);
  // }
};

// 项目阶段
const initProjectPhaseList = async () => {
  try {
    const params = {
      dicType: "flow_project_phase"
    };
    const { code, data } = await api.postDictList(params);
    projectPhaseList.value = data;
    console.log(code, data);
  } catch (err) {
    console.log(err);
  }
};

getProjectList();
initDoucumentTypeList();
initProjectPhaseList();
onMounted(() => {
  if (route.query.mode !== "add") {
    getDetail();
  }
});
</script>

<style lang="scss" scoped>
.content {
  :deep .el-page-header__content {
    font-size: 16px;
  }
  .card-box {
    margin-bottom: 10px;
    &--headerwrap {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    &--setbtn {
      display: flex;
      justify-content: flex-end;
      align-items: center;
      width: 140px;
    }
  }

  .header__wrap {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}
.form-box {
  margin-top: 10px;
}
.form-info {
  margin-bottom: 20px;
}
.header-btns {
  text-align: right;
}

.el-select-dropdown__item {
  height: auto;
  // min-height: 100px;
  // max-height: 274px;
  padding: 0;
  overflow-x: hidden;
  overflow-y: hidden;
}
.el-select-dropdown_item.selected {
  font-weight: normal;
}

.el-select-dropdown_item.selected {
  font-weight: normal;
}

// .tree-option
.tree-option :deep .el-tree-node__content {
  height: auto;
  padding: 0 10px;
}
// .tree-option :deep .el-select-dropdown__list {
//   padding: 0 6px;
// }
.tree-option :deep .el-tree-node__label {
  font-weight: normal;
  padding: 0 10px;
  margin-right: 10px;
}

.el-tree :deep .is-current .el-tree-node__label {
  color: #409eff;
  font-weight: 700;
}
.el-tree :deep .is-current .el-tree-node__children .el-tree-node__label {
  color: #606266;
  font-weight: normal;
}
.default-option :deep .el-tree-node__label {
  font-weight: normal;
  padding: 0 10px;
  // margin-right: 10px;
}

.default-option {
  padding: 0 10px;
}
</style>
